<template>
  <div>
    <el-upload
      action="/api/v1/upload/picture"
      :on-exceed="handleExceed"
      :data="uploadParams"
      ref="upload"
      drag
      :limit="limit"
      :list-type="'picture-card'"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :file-list="fileList"
    >
      <svg
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        width="20px"
        height="20px"
        style="margin:0 auto;color:#82827e"
        focusable="false"
        aria-hidden="true"
      >
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M17.8395 8.05827C17.1837 5.16226 14.5944 3 11.5 3C7.91015 3 5 5.91015 5 9.5C5 10.0204 5.06115 10.5264 5.17665 11.0114C2.84229 11.1772 1 13.1234 1 15.5C1 17.9853 3.01469 20 5.49995 20H17C20.3137 20 23 17.3137 23 14C23 10.9712 20.7558 8.46659 17.8395 8.05827ZM12.3201 8.26674C12.1347 8.11222 11.8653 8.11222 11.6799 8.26674L6.53047 12.5579C6.35084 12.7076 6.45669 13 6.69051 13H10V17.5C10 17.7761 10.2239 18 10.5 18H13.5C13.7761 18 14 17.7761 14 17.5V13H17.3095C17.5433 13 17.6492 12.7076 17.4695 12.5579L12.3201 8.26674Z"
          fill="currentColor"
        ></path>
      </svg>
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <i class="el-icon-download"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imgUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { calculateSHA512 } from '@/utils/encrypt'
import { uploadFileToCos, deleteUploadFile } from '@/api/cos'

import { getAccessToken } from '@/utils/auth'
export default {
  props: {
    editUrl: {
      type: String,
      required: false
    },
    // 类型
    type: {
      type: String,
      required: false,
      default: 'article'
    }
  },
  watch: {
    editUrl: {
      immediate: true,
      handler(val) {
        // 如果传递了url
        if (val) {
          // 清空fileList
          this.fileList = []

          // 创建一个 file 对象
          const fileObj = {
            name: 'edited-image',
            url: val
          }

          // 将 fileObj 添加到 fileList 中
          this.fileList.push(fileObj)
          this.imgUrl = val
        }
      }
    }
  },
  data() {
    return {
      fileList: [],
      imgUrl: '',
      uploadParams: {
        img: null
      },
      dialogVisible: false,
      disabled: false,
      limit: 1,
      currentFile: null
    }
  },
  computed: {},
  methods: {
    handleExceed(files, fileList) {
      console.log('超出限制')
      // 文件数量超过限制的回调函数
      this.$message.warning(`只能上传 ${this.limit} 个文件`)
    },
    async handleRemove(file) {
      console.log(file)
      // 清空数据
      if (file.status == 'success') {
        if (this.imgUrl) {
          // 整理数据
          const formData = new FormData()
          formData.append('url', this.imgUrl)
          // 检测是否可以删除
          const res = await this.$API.upload.DetectCosRemove(formData)
          if (res.status == 200) {
            // 删除多余图片
            const response = await deleteUploadFile(file.name)
            if (response.statusCode == 200 || response.statusCode == 204) {
              this.fileList = []

              this.imgUrl = ''
            }
          }
          // 如果其他资源引用了
          else if (res.status == 422) {
            this.fileList = []

            this.imgUrl = ''
          }
        }
        // 本地清空数据
        // const index = this.fileList.indexOf(file);
        // console.log(index, this.imgList[index])

        // if (index !== -1) {
        //   // 整理数据
        //   const formData = new FormData()
        //   formData.append('url', this.imgList[index])
        //   // 删除多余图片
        //   const res = await this.$API.upload.DeleteAlreadyUploadFile(formData)
        //   if (res.status == 200 || res.status == 422) {
        //     this.fileList.splice(index, 1);

        //     this.imgList.splice(index, 1);

        //   }
        // }
      }
    },
    // 放大缩略图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    async handleUpload() {
      console.log('file', this.currentFile)
      // 格式校验
      const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
      const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif']

      const fileExtension = this.currentFile.name
        .substring(this.currentFile.name.lastIndexOf('.'))
        .toLowerCase()
      const fileMimeType = this.currentFile.type
      // 检查文件扩展名
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片')
        this.fileList = []
        return
      }

      // 检查文件 MIME 类型
      if (!allowedMimeTypes.includes(fileMimeType)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片')
        this.fileList = []
        return
      }
      // cos存储
      // cos存储
      try {
        const response = await uploadFileToCos(
          this.currentFile,
          this.currentFile.name
        )
        console.log(response)
        this.imgUrl = 'http://' + response.Location
        // 上传成功后将 URL 存储到 Vuex 中
        const { type } = this
        if (type == 'article') {
          this.$bus.$emit('UploadSuccess', this.imgUrl)
        } else if (type == 'video') {
          this.$store.commit('video/SETCOVERURL', this.imgUrl)
        }
        // 上传成功后将文件添加到 fileList 中
        this.fileList.push({
          name: this.currentFile.name,
          url: this.imgUrl
        })
        // 清空当前文件
        this.currentFile = null
      } catch (error) {
        console.error(error)
        this.$message.error('上传失败')
      }
      // const fileReader = new FileReader()
      // // 以8192字节的形式读取文件
      // const chunkSize = 8192;
      // let currentByte = 0;
      // // 文件读取
      // fileReader.onload = async () => {
      //   const arrayBuffer = fileReader.result;
      //   const uint8Array = new Uint8Array(arrayBuffer);
      //   // 格式转换
      //   const fileBlob = new Blob([arrayBuffer], { type: this.currentFile.type });
      //   // 生成hash值
      //   const file_hash = await calculateSHA512(fileBlob);
      //   const datas = this.$qs.stringify({ file_hash })
      //   console.log(file_hash, datas)
      //   try {
      //     // 验证文件是否存在
      //     const res = await this.$API.video.CheckExist(datas)
      //     console.log(res)
      //     const { type } = this

      //     // 如果存在秒传地址
      //     if (res && res.status == 200) {
      //       this.videoUrl = res.data.url
      //       if (type == 'article') {
      //         this.$bus.$emit("UploadSuccess", res.data.url)
      //       } else if (type == 'video') {
      //         this.$store.commit("video/SETCOVERURL", res.data.url)
      //       }
      //       return;
      //     }
      //     // 整理数据
      //     const formData = new FormData()
      //     formData.append('img', this.currentFile)
      //     // 上传图片
      //     const response = await this.$API.article.uploadImage(formData)
      //     console.log(response)
      //     if (response.status == 200) {
      //       // this.fileList.push(this.currentFile)
      //       this.imgUrl = response.data.url
      //       // 数据传递
      //       console.log(type)
      //       if (type == 'article') {
      //         this.$bus.$emit("UploadSuccess", response.data.url)
      //       } else if (type == 'video') {
      //         this.$store.commit("video/SETCOVERURL", response.data.url)

      //       }
      //     }
      //   } catch (error) {
      //     this.$message.error("文件检查请求失败")
      //     return;
      //   }
      // }
      // fileReader.readAsArrayBuffer(this.currentFile);
    },
    async beforeUpload(file) {
      console.log(file)
      this.currentFile = file
      // 阻止自动上传
      return false
    }
  }
}
</script>
<style scope>
</style>